package com.thornbird.vehiclerecycling.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class EncryptUtil {

    public static final String MD5 = "MD5";

    public static String getOrderedData(Object source, String... ignoreKeys) {
        StringBuffer data = new StringBuffer();
        List<String> ignoreKeyList = new ArrayList<>();
        if (ignoreKeys != null) {
            ignoreKeyList = Arrays.asList(ignoreKeys);
        }
        Map<String, Object> dataMap = JsonUtil.parseObject(JsonUtil.toJsonString(source),
                new HashMap<String, Object>().getClass());
        Map<String, String> treeMap = new TreeMap<>(new KeyComparator());
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            if (!ignoreKeyList.contains(entry.getKey())) {
                treeMap.put(entry.getKey(), entry.getValue() == null ? null : String.valueOf(entry.getValue()));
            }
        }
        Iterator<String> iterable = treeMap.keySet().iterator();
        while (iterable.hasNext()) {
            String key = iterable.next();
            String value = treeMap.get(key);
            data.append(String.format("%s=%s;", key, value));
        }
        return data.toString();
    }

    public static String md5(String text) {
        String result = "";
        try {
            result = new String(text);
            MessageDigest md = MessageDigest.getInstance(MD5);
            result = bytesToHexString(md.digest(result.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static int md52int(String md5) {
        int result = 0;
        if (md5 == null || md5.isEmpty()) {
            return result;
        }

        for (char c : md5.toCharArray()) {
            int value = c;
            result = result + c;
        }
        return result;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (int i = 0, count = bytes.length; i < count; i++) {
            String value = Integer.toHexString(bytes[i] & 0xFF);
            result.append(value.length() == 1 ? "0" + value : value);
        }
        return result.toString();
    }


    static class KeyComparator implements Comparator<String> {

        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }

    }

}
